package com.bida.core.mongo;

import java.net.UnknownHostException;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;

/**
 * This template defines the MongoDB connection properties for the "default"
 * connection. Note how it receives configuration items from Spring, and uses
 * base class getters/setters instead of defining its own. This way we can
 * easily define multiple such connection properties and don't make mistakes.
 * 
 */
@Configuration
@ConfigurationProperties(locations = "application.properties", prefix = "spring.data.mongodb")
public class MongoTemplateForDefault extends BaseMongoTemplate {

    private Mongo mongo;

    // IMPORTANT, this name is the same as the class name, as Springboot
    // @EnableAutoConfiguration needs a
    // "default" mongoTemplate
    /**
     * 
     * @return MongoTemplate for Default
     * @throws UnknownHostException
     *             Unknow Host
     */
    @Bean(name = "mongoTemplate")
    @DependsOn(value = "defaultMongoClient")
    public MongoTemplate mongoTemplate() throws UnknownHostException {
        return super.createTemplate(this.mongo);
    }

    /**
     * 在
     * {@link org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration}
     * 中可以看到，如果Mongo没有被加载， 那么Spring会加载Mongo.我们之前的代码，直接通过new的方式创建了Mongo实例，这样会导致
     * Spring启动的时候，会认为Mongo并没有被加载，于是会自动加载Mongo。但是Spring
     * 默认的加载方式，不支持我们配置文件的“,”方式，在启动的时候会出现 Invalid character ',' in key part of
     * property的错误。因此需要我们自己加载Mongo Bean. 建议：在Spring中尽量不要自己new Object。
     * 
     * @return Mongo for Default
     * @throws UnknownHostException
     *             Unknow Host
     */
    @Bean(name = "defaultMongoClient")
    @Primary
    public Mongo mongo() throws UnknownHostException {
        mongo = new MongoClient(getMongoReplicationSet(), getMongoCredentials());
        return mongo;
    }

}
